package cn.hao.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;

@RestController
public class ExcelController {
	
	@RequestMapping("/getExcel")
	private String home(HttpServletResponse response) throws IOException {
		writeExcel(response,"123","111");
//		OutputStream out = new FileOutputStream("C:/Users/Li/Desktop/123.xlsx");
//		try {
//			ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, false);
//			// 写第一个sheet, sheet1 数据全是List<String> 无模型映射关系
//			Sheet sheet1 = new Sheet(1, 0);
//			sheet1.setSheetName("第一个sheet");
//			writer.write0(getListString(), sheet1);
//			writer.finish();
//			System.out.println("完成");
//			return "ok";
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			try {
//				out.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
		return "";
	}

	public static void writeExcel(HttpServletResponse response, String fileName, String sheetName) throws IOException {
		// 创建本地文件
		String filePath = fileName + ".xlsx";
		File dbfFile = new File(filePath);
		if (!dbfFile.exists() || dbfFile.isDirectory()) {
			dbfFile.createNewFile();
		}
		fileName = new String(filePath.getBytes(), "ISO-8859-1");
		response.addHeader("Content-Disposition", "filename=" + fileName);
		OutputStream out = response.getOutputStream();
		try {
			ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
			Sheet sheet = new Sheet(1, 0);
			sheet.setSheetName(sheetName);
			writer.write0(getListString(), sheet);
			writer.finish();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static List<List<String>> getListString() {
		List<List<String>> lists = new ArrayList<>();
		List<String> list = new ArrayList<>();
		list.add("123胜多负少顶起");
		list.add("123");
		ArrayList<String> list1 = new ArrayList<>();
		list1.add("1");
		list1.add("1地方是否");
		lists.add(list);
		lists.add(list1);
		return lists;
	}

}
